package com.hang.exception.handler;

import com.hang.common.Result;
import com.hang.exception.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler({SQLException.class})
    public Result sqlException(SQLException sqlException) {
        String msg = sqlException.getMessage();
        log.error("数据库错误...{}", msg);
        return result("服务器内部异常", HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
    }

    @ExceptionHandler({MyException.class})
    public Result shiftException(MyException myException) {
        String msg = myException.getMessage();
        log.error("业务错误...{}", msg);
        return result(msg,myException.getCode(), msg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result validationBodyException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        FieldError fieldError = result.getFieldError();
        AtomicReference<String> messageRef = new AtomicReference<>();
        Optional.ofNullable(fieldError).ifPresent(fe -> messageRef.set(fe.getDefaultMessage()));
        log.error("参数异常:{}",messageRef.get());
        return result(messageRef.get(), HttpStatus.BAD_REQUEST.value(), messageRef.get());
    }

    private Result result(String errorMsg, int code, String data) {
        Result<Object> result = new Result<>();
        result.setCode(code);
        result.setMessage(errorMsg);
        result.setData(data);
        return result;
    }
}